package ThreadDemo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-10-30
 * Time: 21:51
 */
//CountDownLatch类方法使用
public class CountDownLatchTest {
    public static void main(String[] args) throws InterruptedException {
        //创建CountDownLatch实例
        //CountDownLatch实例只能使用一次，当初始化完成计数器大小后，就没办法在对计数器进行重新复制操作
        //每完成一个子任务，计数器-1，完成所有子任务，计数器值等于零
        CountDownLatch latch = new CountDownLatch(10);//描述有多个子任务要完成
        //把一个任务拆分成10个子任务,并交给多线程完成,每个线程执行其中一个任务
        for (int i = 0; i < 10; i++) {
            int id = i;
            Thread t = new Thread(() -> {
                try {
                    System.out.println("子任务 " + id + " 执行前");
                    Thread.sleep(1000);
                    System.out.println("子任务 " + id + " 执行完成");
                    latch.countDown();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            });
            t.start();
        }
        latch.await();
        System.out.println("所有任务执行完成");
    }
}
